package com.ddtech.utils;

import cn.hutool.core.util.ZipUtil;

import java.io.File;
import java.nio.charset.Charset;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author bin_pu
 * @since 2020/11/9
 */
public class MyZipUtils {

    /**
     * 递归解压文件
     *
     * @param unFile
     * @param delZip
     * @return
     */
    public static File loopUnzip(File unFile, boolean delZip) {
        String suffix = com.ddtech.utils.FileUtil.getExtensionName(unFile.getName());
        if ("zip".equalsIgnoreCase(suffix)) {
            File unzip = unzip(unFile, delZip);
            List<File> files = cn.hutool.core.io.FileUtil.loopFiles(unzip);
            for (File file : files) {
                loopUnzip(file, delZip);
            }
            unFile = unzip;
        }
        return unFile;
    }

    public static File unzip(File file, boolean delZip) {
        File unZipFile;
        try {
            unZipFile = ZipUtil.unzip(file, Charset.forName("UTF-8"));
        } catch (IllegalArgumentException e) {
            unZipFile = ZipUtil.unzip(file, Charset.forName("GBK"));
        } finally {
            if (delZip) {
                FileUtil.del(file);
            }
        }
        return unZipFile;
    }
}
